//#if isYomob
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Together;
using UnityEngine;

namespace Topifish.Ads {
    /// <summary>
    /// Yomob广告代理,对接Yomob平台的广告业务
    /// </summary>
    public class YomobAgent : MonoBehaviour {
        static YomobAgent instance;
        public static YomobAgent GetInstance {
            get {
                if (instance == null) {
                    GameObject gg = new GameObject("YomobAgent");
                    MonoBehaviour.DontDestroyOnLoad(gg);
                    instance = gg.AddComponent<YomobAgent>();
                }
                return instance;
            }
        }
        bool isTestAd = false;
        public static string appId = "5o25S500D6264xOSYU1L";
        void Awake() {
            isInitSuccess = false;
            TGSDK.SetDebugModel(isTestAd);
            Debug.Log("Yomob广告__初始化");
            TGSDK.SDKInitFinishedCallback = (string msg) => {
                //TGSDK.TagPayingUser(TGPayingUser.TGLargePaymentUser, "CNY", 1080, 105600);
                TGSDK.TagPayingUser(TGPayingUser.TGLargePaymentUser, "USD", 1080, 105600);
                Debug.Log("Yomob广告__初始化完成___TGSDK finished : " + msg);
                Debug.Log("Yomob广告__用户数据保护条款==TGSDK GetUserGDPRConsentStatus = " + TGSDK.GetUserGDPRConsentStatus());
                TGSDK.SetUserGDPRConsentStatus("yes");
                Debug.Log("Yomob广告__是否年龄限制用户==TGSDK GetIsAgeRestrictedUser = " + TGSDK.GetIsAgeRestrictedUser());
                TGSDK.SetIsAgeRestrictedUser("no");
                float bannerHeight = (float)(Screen.height) * 0.123f;
                bannerHeight = Screen.height * 105 / 1334;
#if UNITY_ANDROID
                TGSDK.SetBannerConfig(gameBoxAdScenes[(int)E_AdType.e03_Banner01], "TGBannerNormal", 0, Display.main.systemHeight - 1 * bannerHeight, Display.main.systemWidth, bannerHeight, 120);
#elif UNITY_IOS
                TGSDK.SetBannerConfig("banner0", "TGBannerNormal", 0, Display.main.systemHeight - bannerHeight, Display.main.systemWidth, bannerHeight, 30);
                TGSDK.SetBannerConfig("banner1", "TGBannerNormal", 0, Display.main.systemHeight - 0.6f * bannerHeight, Display.main.systemWidth, bannerHeight, 30);
                TGSDK.SetBannerConfig("banner2", "TGBannerNormal", 0, Display.main.systemHeight - 3 * bannerHeight, Display.main.systemWidth, bannerHeight, 30);
#endif
                Debug.Log("Yomob广告__单位尺寸== " + Display.main.systemHeight + "___" + Display.main.systemWidth + "___" + bannerHeight);
                PreloadAd();
            };
            //Game Box Group

            //测试账号
            //string appId = "59t5rJH783hEQ3Jd7Zqr";
#if UNITY_IOS && !UNITY_EDITOR
		    TGSDK.Initialize (appId);
#elif UNITY_ANDROID// && !UNITY_EDITOR
            TGSDK.Initialize(appId);
#endif
        }
        void Start() {

        }

        public void Init() { }
        string[] bannerPlatform = new string[] { "tgadsdk", "inmobi", "admob", "facebook" };
        string[] adPlatform = new string[] { "inmobi", "admob", "facebook", "adcolony", "applvin", "unityads", "vungle", "tgadsdk" };

        string[] scenes;
        int sceneIndex = 0;
        string[] sceneNames;

        int[] tryCount = new int[5] { 0, 0, 0, 0, 0 };

        /// <summary>
        /// 短时间重新加载插页广告的次数
        /// </summary>
        const int MaxTryCount = 10;

        /// <summary>
        /// 广告加载失败后，短时间延迟加载的间隔时间
        /// </summary>
        const float DelayTry = 2.0f;

        bool underShow = false;

        /// <summary>
        /// 广告多次加载失败后，下一次重复加载的间隔时间；
        /// </summary>
        const float NextCycleDelayTry = 3 * 60.0f;
#if UNITY_ANDROID
        //Game Box Group
        public static string[] gameBoxAdScenes = new string[] { "C3O8pO6z6eDVcsEBntq", "DwYfmSfSiXWpHxkkyv9", "NbKyK17oCtj07FgnQeI", "8dKXguPZIfZp4f89DeL", "banner2", };
        //SDK测试账号
        //string[] tempScenes = new string[] { "XItNxyTVj5KOLmj2MS0", "hiRZYZxDI7c2LaOgrE7", "TsqVg2tWch0xuzu0AnW", "banner0", "banner1", };
#elif UNITY_IOS
       public static string[] gameBoxAdScenes = new string[] {  "D6mHM4ReRGUdph0CwZw","qfJDzBR0aMUaVIWF2Q7", "CyvZlf6F0h2IsHJJi6s", "banner0", "banner1", };
#else
       public static string[] gameBoxAdScenes;
#endif
        //string[] tempSceneMames = new string[] { "静态插屏广告(XItN)", "奖励视频(hiRZ)", "插屏视频广告(TsqV)", "0-Banner(bann)", "1-Banner(bann)", };
        enum E_AdType {
            e00_Interstitial = 0,
            e01_RewardVideo = 1,
            e02_InterstitialVideo = 2,
            e03_Banner01 = 3,
            e04_Banner02 = 4,
        }
        /// <summary>
        /// 奖励视频结果回调
        /// </summary>
        public event Action<E_AdCallbackType> d_RewardVideoResultCallBack;
        /// <summary>
        /// 插页广告结果回调
        /// </summary>
        public event Action<E_AdCallbackType> d_InterstitialResultCallBack;
        int ShowBannerFailNumber;
        public void PreloadAd() {
            TGSDK.PreloadAdSuccessCallback = (string msg) => {
                Debug.Log("Yomob广告__预加载广告完成__PreloadAdSuccessCallback : " + msg);
                scenes = Regex.Split(msg, ",", RegexOptions.IgnoreCase);
                sceneNames = new string[scenes.Length];
                for (int i = 0; i < scenes.Length; i++) {
                    string scene = scenes[i];
                    string sceneName = TGSDK.GetSceneNameById(scene);
                    sceneNames[i] = sceneName + "(" + scene.Substring(0, 4) + ")";
                    Debug.Log("Yomob广告__场景== " + scenes[i] + "______" + sceneNames[i]);
                }
                isInitSuccess = true;
                CheckAdStatus();
            };
            TGSDK.PreloadAdFailedCallback = (string msg) => {
                Debug.Log("Yomob广告__预加载失败--PreloadAdFailedCallback : " + msg);
                PreloadAd();
            };
            TGSDK.InterstitialLoadedCallback = (string msg) => {
                Debug.Log("Yomob广告__插页广告加载--InterstitialLoadedCallback : " + msg);
                IsInterstitialReady();
            };
            TGSDK.InterstitialVideoLoadedCallback = (string msg) => {
                Debug.Log("Yomob广告__插页视频加载--InterstitialVideoLoadedCallback : " + msg);
                IsOffLineRewardedVideoReady();
            };
            TGSDK.AwardVideoLoadedCallback = (string msg) => {
                Debug.Log("Yomob广告__奖励视频加载--AwardVideoLoadedCallback : " + msg);
                IsRewardedVideoReady();
            };



            TGSDK.AdShowSuccessCallback = (string scene, string msg) => {
                Debug.Log("Yomob广告__AdShow : " + scene + " 成功-SuccessCallback : " + msg);
                if (scene == gameBoxAdScenes[(int)E_AdType.e00_Interstitial]) {
                    d_InterstitialResultCallBack(E_AdCallbackType.e08_onAdOpened);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e01_RewardVideo]) {
                    d_RewardVideoResultCallBack(E_AdCallbackType.e08_onAdOpened);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e02_InterstitialVideo]) {
                    d_InterstitialResultCallBack(E_AdCallbackType.e08_onAdOpened);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e03_Banner01]) {
                    tryCount[(int)E_AdType.e03_Banner01] = 0;
                }
            };
            TGSDK.AdShowFailedCallback = (string scene, string msg, string err) => {
                Debug.Log("Yomob广告__AdShow : " + scene + " 失败-FailedCallback : " + msg + ", " + err);

                if (gameBoxAdScenes[(int)E_AdType.e03_Banner01] == scene && underShow) {
                    RefreshBanner(true, scene, msg);
                }
                if (scene == gameBoxAdScenes[(int)E_AdType.e00_Interstitial]) {
                    d_InterstitialResultCallBack(E_AdCallbackType.e12_onAdClosed);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e01_RewardVideo]) {
                    d_RewardVideoResultCallBack(E_AdCallbackType.e12_onAdClosed);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e02_InterstitialVideo]) {
                    d_InterstitialResultCallBack(E_AdCallbackType.e12_onAdClosed);
                }
            };
            TGSDK.AdCloseCallback = (string scene, string msg, bool award) => {
                Debug.Log("Yomob广告__AdClose : " + scene + " 关闭-Callback : " + msg + " Award : " + award);
                if (scene == gameBoxAdScenes[(int)E_AdType.e00_Interstitial]) {
                    if (award) {
                        d_InterstitialResultCallBack(E_AdCallbackType.e16_onAdRewarded);
                    }
                    d_InterstitialResultCallBack(E_AdCallbackType.e12_onAdClosed);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e01_RewardVideo]) {
                    if (award) {
                        d_RewardVideoResultCallBack(E_AdCallbackType.e16_onAdRewarded);
                    }
                    d_RewardVideoResultCallBack(E_AdCallbackType.e12_onAdClosed);
                } else if (scene == gameBoxAdScenes[(int)E_AdType.e02_InterstitialVideo]) {
                    if (award) {
                        d_InterstitialResultCallBack(E_AdCallbackType.e16_onAdRewarded);
                    }
                    d_InterstitialResultCallBack(E_AdCallbackType.e12_onAdClosed);
                }
            };
            TGSDK.AdClickCallback = (string scene, string msg) => {
                Debug.Log("Yomob广告__AdClick : " + scene + " 事件-Callback : " + msg);
            };
            Debug.Log("Yomob广告__开始预加载广告___");
            TGSDK.PreloadAd();
        }

        private void RefreshBanner(bool failedTrigger, string scene, string msg) {

            if (failedTrigger) {
                tryCount[(int)E_AdType.e03_Banner01]++;
                Debug.LogFormat("Yomob广告__关闭横幅____{0}________{1}___广告尝试次数={2}", scene, msg, tryCount[(int)E_AdType.e03_Banner01]);
                TGSDK.CloseBanner(scene);
                underShow = false;
                if (tryCount[(int)E_AdType.e03_Banner01] < MaxTryCount) {
                    S_DelayedEvent(DelayTry, delegate () {
                        TryShowBanner01();
                    });
                } else {
                    tryCount[(int)E_AdType.e03_Banner01] = 0;
                    S_DelayedEvent(NextCycleDelayTry, delegate () {
                        TryShowBanner01();
                    });
                }
            } else {
                S_DelayedEvent(DelayTry, delegate () {
                    TryShowBanner01();
                });
            }
        }

        public void StartLoadAds() {
            S_DelayedEvent(1, delegate () {
                TryShowBanner01();
            });
        }
        public bool IsInitComplete { get { return isInitSuccess; } }
        bool isInitSuccess;
        void CheckAdStatus() {
            string sceneid = gameBoxAdScenes[(int)E_AdType.e03_Banner01];
            for (int i = 0; i < adPlatform.Length; i++) {
                if (TGSDK.CouldShowAd(sceneid, adPlatform[i])) {
                    Debug.Log("Yomob广告__横幅广告 ready------" + adPlatform[i] + "___" + sceneid);
                } else {
                    Debug.Log("Yomob广告__横幅广告 not ready-----" + adPlatform[i] + "___" + sceneid);
                }
            }
        }

        public bool CurrentDeviceIsSupport() {
            return true;
        }

        public bool IsInterstitialReady() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return false;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e00_Interstitial];
            bool isCanShowAd = TGSDK.CouldShowAd(sceneid);
            Debug.Log("Yomob广告__插页广告-------是否可用-------" + isCanShowAd);
            return isCanShowAd;
        }

        public bool IsOffLineRewardedVideoReady() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return false;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e01_RewardVideo];
            bool isCanShowAd = TGSDK.CouldShowAd(sceneid);
            Debug.Log("Yomob广告__离线收益-------是否可用-------" + isCanShowAd);
            return isCanShowAd;
        }

        public bool IsRewardedVideoReady() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return false;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e01_RewardVideo];
            bool isCanShowAd = TGSDK.CouldShowAd(sceneid);
            Debug.Log("Yomob广告__激励广告-------是否可用-------" + isCanShowAd);
            return isCanShowAd;
        }

        public void ShowInterstitial() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e00_Interstitial];
            if (isTestAd) {
                TGSDK.ShowTestView(sceneid);
            } else {
                if (TGSDK.CouldShowAd(sceneid)) {
                    Debug.Log("Yomob广告__插页广告___开始显示");
                    TGSDK.ShowAd(sceneid);
                } else {
                    Debug.Log("Yomob广告__插页广告 could not to show");
                }
            }
        }

        public void ShowOffLineRewardedVideo() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e01_RewardVideo];
            if (isTestAd) {
                TGSDK.ShowTestView(sceneid);
            } else {
                if (TGSDK.CouldShowAd(sceneid)) {
                    Debug.Log("Yomob广告__离线奖励视频___开始显示");
                    TGSDK.ShowAd(sceneid);
                } else {
                    Debug.Log("Yomob广告__离线奖励视频  could not to show");
                }
            }
        }

        public void ShowRewardedVideo() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e01_RewardVideo];
            if (isTestAd) {
                TGSDK.ShowTestView(sceneid);
            } else {
                if (TGSDK.CouldShowAd(sceneid)) {
                    Debug.Log("Yomob广告__奖励视频___开始显示");
                    TGSDK.ShowAd(sceneid);
                } else {
                    Debug.Log("Yomob广告__奖励视频  could not to show");
                }
            }
        }
        public void TryShowBanner01() {
            if (isInitSuccess == false) {
                Debug.Log("Yomob广告__预加载没有完成");
                return;
            }
            string sceneid = gameBoxAdScenes[(int)E_AdType.e03_Banner01];
            if (isTestAd) {
                underShow = true;
                TGSDK.ShowTestView(sceneid);
            } else {
                if (TGSDK.CouldShowAd(sceneid)) {
                    Debug.Log("Yomob广告__横幅广告____开始显示-----__" + sceneid);
                    underShow = true;
                    TGSDK.ShowAd(sceneid);
                } else {
                    Debug.Log("Yomob广告__横幅广告 could not to show_____" + sceneid);
                    RefreshBanner(false, "", "");
                }
                //for (int i = 0; i < bannerPlatform.Length; i++) {
                //    if (TGSDK.CouldShowAd(sceneid, bannerPlatform[i])) {
                //        Debug.Log("Yomob广告__横幅广告____开始显示------"+ bannerPlatform[i]+"___"+ sceneid);
                //        TGSDK.ShowAd(sceneid, bannerPlatform[i]);
                //        break;
                //    } else {
                //        Debug.Log("Yomob广告__横幅广告 could not to show-----"+ bannerPlatform[i] + "___" + sceneid);
                //    }
                //}
            }
        }

#region 工具方法
        void S_DelayedEvent(float time, Action zEvent) {
            StartCoroutine(I_DelayedEvent(time, zEvent));
        }
        IEnumerator I_DelayedEvent(float time, Action zEvent) {
            yield return new WaitForSeconds(time);
            zEvent();
        }
#endregion
    }
    public abstract class C_Config {
        public string appId;
        public Dictionary<int, string> keyDic = new Dictionary<int, string>();
    }

}
//#endif